﻿

using MediatR;
using Microsoft.EntityFrameworkCore;
using ProductIntory.Domains;
using ProductIntory.ErrorCodes;
using ProductIntory.Infrastructures.Interface;
using ProductIntory.Read.Apis.Application.Command;

namespace ProductIntory.Read.Apis.Application.CommandHandler
{
    public class CheckEnfCommandHandler : IRequestHandler<CheckEnfCommand, ApiResult<List<Products>>>
    {
        IBaseRepository<Products> Products;
        IBaseRepository<SalesOrderModel> SalesOrderModel;

        public CheckEnfCommandHandler(IBaseRepository<Products> Products, IBaseRepository<SalesOrderModel> SalesOrderModel)
        {
            this.Products = Products;
            this.SalesOrderModel = SalesOrderModel;
        }

        public async Task<ApiResult<List<Products>>> Handle(CheckEnfCommand request, CancellationToken cancellationToken)
        {
            List<Products> products = new List<Products>();
            if (request.id > 0)
            {
                var product = Products.GetAll().Where(c => c.Productions_Id == request.id).FirstOrDefault();
                    var list =await SalesOrderModel.GetAll().Where(c => c.SalesOrderCode == product.ProductCategory).FirstOrDefaultAsync();
                    products.Add(product);
                    if (list.SaleNumder > product.CurrentStock)
                    {
                        products.First().Isdel = true;
                        return new ApiResult<List<Products>>
                        {
                            Code = ApiEnum.success,
                            Message = "库存充足",
                            Data = products
                        };
                    }
                    else 
                    {
                        products.First().Isdel = false;
                        return new ApiResult<List<Products>>
                        {
                            Code = ApiEnum.error,
                            Message = "库存不够了",
                            Data = products
                        };
                    }
                
            }
            else
            {
                return new ApiResult<List<Products>>
                {
                    Code = ApiEnum.success,
                    Message = "未找到",
                    Data = null
                };
            }
            
        }
    }
}
